<?php
use Overtrue\Wechat\Url;
use Overtrue\Wechat\Notice;

class HomeController extends BaseController {
	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/
	public function search(){
        $validator = Validator::make(Input::all(),
            array(
                'key' => 'required'
            )
        );
        do{
            if($validator->fails()){
                $response = Lang::get("error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }
//            $key = iconv('UTF-8', 'GB2312',Input::get('key'));
            $key = Input::get('key');
            $response = Scws::participle($key);
        }while(false);
        Log::info("info", array("system" => "api" ,"event" => "search", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

	public function showWelcome()
	{
		return View::make('hello');
	}

    public function shortUrl(){

        $appId  = 'wx664e3e4c6b3b1267';
        $secret = '688351e34b6b6b4a46e7bf3c32cdf8a9';
        $url = new Url($appId, $secret);
        $shortUrl = $url->short('http://www.yangche1hao.com');
        return $shortUrl;
    }

    public function notice(){
        $appId  = 'wxb33f3b8d52352c40';
        $secret = 'a5aeb742da23e83e39059d797b2f3f28';
        $notice = new Notice($appId, $secret);
//        $userId = 'oxJpzs70HSjURxDs6d4y7_pZtssw';
        $userId = 'oxJpzs3aFRG5I-DEpq8RcLHLp2cg';
        $templateId = 'aKYgGm3yl4MpH_JC7sHzrc7rW5DAaTLSvMwEsJdd8mk';
        $url = 'http://wechat.anhui-tech.com';
        $color = '#FF0000';
        $data = array(
            "first"    => "恭喜你购买成功！",
            "name" => "洗车券",
            "price" => "39.8元",
            "date" => "2017年3月23日",
            "remark"   => "欢迎再次购买！",
        );

        $messageId = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();
        return $messageId;
    }

    /*
   * 生成图片验证码
   *
   * */
    public function img_code(){
        $validator = Validator::make(Input::all(),
            array(
                'phone' => 'required|regex:/^1[0123456789][0-9]{9}$/',
            )
        );
        do{
            $messages = $validator->messages();
            if($messages->has('phone')) {
                $response = Lang::get('error.user_phone_format_error_10007');
                return json_encode($response);
            }
            if ($validator->fails()) {
                $response = Lang::get("error.user_sms_check_code_args_error_1001");
                return json_encode($response);
            }
            $phone = Input::get('phone');
            $captcha = new Captcha($phone);
            $captcha->create();
        }while(false);
        Log::info("info", array("system" => "wxw" ,"event" => "img_code", 'input' =>Input::all()));

    }
    /*
    * 用户申请短信验证码
    *
    * */
    public function sms_check_code()
    {
        $validator = Validator::make(Input::all(),
            array(
                'phone' => 'required|regex:/^1[0123456789][0-9]{9}$/',
                'code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            $messages = $validator->messages();
            if($messages->has('phone')) {
                $response = Lang::get('error.user_phone_format_error_10007');
                break;
            }
            if ($validator->fails()) {
                $response = Lang::get("error.user_sms_check_code_args_error_1001");
                break;
            }

            //todo default area for test
            //获取手机号
            $phone = Input::get('phone');
            $area = '010';
//            $area = Input::get('area');
            $time_out_default = Config::get("user.check_code_time_out");
            $captcha = new Captcha(Input::get('phone'));
            $check = $captcha->check(Input::get('code'));
            if(!$check){
                $response = array("code" => 2,"msg"=>"图片验证码不正确");
                break;
            }
            //同一个手机号一天发送登录验证码不能超过3次
            $day_start = date('Y-m-d',time()). ' 00:00:00';
            $day_stop =  date('Y-m-d',time()). ' 23:59:59';
            $day_count = SmsSendRecords::where('phone',$phone)->whereBetween('created_at',array($day_start,$day_stop))->count();
            if($day_count >3){
                $response = array("code" => 1,"msg"=>"验证码下发太频繁 "."[".$day_count."]"."[".Request::getClientIp()."]" );
                break;
            }
            //检查手机号是否下发验证码
            $record = UserCheckCode::getCheckCode($phone,$area);
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    $response = array("code" => 1,"msg"=>"验证码下发太频繁");
                    break;
                }else{ //超过限时
                    UserCheckCode::delCheckCode($phone,$area);
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();

            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'您的验证码是'.$check_code.'，有效期6分钟，感谢您选择安惠车服，安惠车服为您提供一站式养车服务。');
                $status = SmsSendRecords::selectSmsRecord($sms_send_record_id);
                if(isset($status->status) && $status->status == 1){
//                $status = 1;
//                $sms_send_record_id = 1;
//                if($status  == 1){
                    $response = array("code" => 0,"msg"=>"感谢您使用安惠养车，本次登录验证码为：".$check_code);
                }else{
                    $response = Lang::get("error.user_sms_check_code_send_error_10003");
                    break;
                }

            } catch (Exception $e) {
                Log::error("error", array("system" => "demo" ,"event" => "sms_check_code", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_10003");
                break;
            }

            //记录数据库
            $data = array(
                'phone' => $phone,
                'area' => $area,
                'check_code' => $check_code,
                'created_at' => Common::num2DateTime(time()),
                'out_time_at' => Common::num2DateTime(time() + $time_out_default),
                'send_id' => $sms_send_record_id,
            );

            try {
                UserCheckCode::insCheckCode($data);
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "sms_check_code", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_create_error_1002");
                break;
            }

        } while (false);

        Log::info("info", array("system" => "wxw" ,"event" => "sms_check_code", 'input' =>Input::all() ,"output" => $response));
        //return json_encode($response);
        return $response;
    }
    /*
       * @Author:      kc
      * @DateTime:    2017-02-22 17:50:32
      * @Description: 天气预报(调用新浪天气api)
      * */
    public function weather(){
        $validator = Validator::make(Input::all(),
            array(
                'city' => 'required'
            )
        );
        do{
            if($validator->fails()){
                $response = Lang::get("error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            try{
                $city = iconv('UTF-8', 'GB2312',Input::get('city'));
                $url = 'http://php.weather.sina.com.cn/xml.php?city='.$city.'&password=DJOYnieT8234jlsK&day=0';
                $weather = simplexml_load_string(file_get_contents($url));
                
            }catch (Exception $e){
                $response = Lang::get("error.weather_forecast_error_30000");
                break;
            }
            
            if(!isset($weather->Weather)){
                $response = Lang::get("error.weather_forecast_error_30000");
                break;
            }else{
                $weather_data =  array(
                    'city' => (String)$weather->Weather->city,
                    'status' => (String)$weather->Weather->status1,
                    'car_wash'=> (String)$weather->Weather->xcz_l,
                    'temperature' => (String) $weather->Weather->temperature1.'°C ~ '.$weather->Weather->temperature2.'°C',
                );
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => $weather_data,
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "weather", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /*
      * @Author:      kc
     * @DateTime:    2017-02-23 10:36:32
     * @Description: 限行接口(调用路帮网接口)
     * */
    public function limitLine(){
        $validator = Validator::make(Input::all(),
            array(
                'city' => 'required'
            )
        );
        do{
            if($validator->fails()){
                $response = Lang::get("error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $url = "http://www.loopon.cn/api/v1/trafficlimit/number/getCityList";
            $post_data = array ("apikey" => "1e68f8f0-dad0-0134-8667-0242c0a80007");
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // post数据
            curl_setopt($ch, CURLOPT_POST, 1);
            // post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $city_code = curl_exec($ch);
            curl_close($ch);
            if($city_code === FALSE ){
                $response = Lang::get('error.run_exception');
                break;
            }
            $city = '';
            $city_code = json_decode($city_code,true);

            if(!empty($city_code)){
                if(!empty($city_code['data'])){
                    foreach($city_code['data'] as $v){
                        if(strstr($v['cityname'],Input::get('city'))!== false) {
                            $city = $v['city'];
                        }
                    }
                }
            }

            if($city == ''){
                //$number = '未知';
                //获取ahp后台配置
                //$weekarray=array("日","一","二","三","四","五","六");
                $weekarray=array("7","1","2","3","4","5","6");
                $week = $weekarray[date("w",strtotime(date("Y-m-d",time())))];
                $city_name = Input::get('city');
                $city_id = ResourceCityType::getCity($city_name);
                if(!is_null($city_id)){
                    $limit = AhpCityLimitCar::getLimit($city_id->id, $week);
                    if(!is_null($limit)){
                        $number = $limit->limit_car;
                    }else{
                        $number = '未知';
                    }
                }else{
                    $number = '未知';
                }
            }else{
                $limit_line_url = "http://www.loopon.cn/api/v1/trafficlimit/number/getCityLimit";
                $post_data = array ("apikey" => "1e68f8f0-dad0-0134-8667-0242c0a80007","city" => $city);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $limit_line_url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                // post数据
                curl_setopt($ch, CURLOPT_POST, 1);
                // post的变量
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
                $city_limit_line = curl_exec($ch);
                curl_close($ch);
                if($city_code === FALSE ){
                    $response = Lang::get('error.run_exception');
                    break;
                }
                $city_limit_line = json_decode($city_limit_line);
                $city_limit_number = '';
                //TODO::外地车限行是$city_limit_line->foreigncar,暂时不查外地车限行
                if(!empty($city_limit_line->localcar)){
                    $city_limit_number = $city_limit_line->localcar[0]->number;

                }
                if(!empty($city_limit_line->allcars)){
                    $city_limit_number =  $city_limit_line->allcars[0]->number;
                }
                //TODO::只查本地车限行
                if($city_limit_number == ''){
                    $number = '不限行';
                }else{
                    $number = str_replace(',','/',substr($city_limit_number,0,strpos($city_limit_number,';')));
                }
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'number' => $number,
                )
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "limitLine", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /*
     * @Author:      sqq
     * @DateTime:    2018-08-24 11:16:32
     * @Description: 限行接口(调用阿里云接口)
     * @link: http://www.activity.com/wechat/api3.0/aly_limit_line?city=%E6%B2%A7%E5%B7%9E
     * */
    public function ALYlimitLine(){
        $validator = Validator::make(Input::all(),
            array(
                'city' => 'required'
            )
        );
        do{
            if($validator->fails()){
                $response = Lang::get("error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }

            $city = Input::get('city');

            if(preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $city) === 1){
                $city = Pinyin::getPinyin($city);
            }

            if($city == ''){
                $response = Lang::get('error.run_exception');
                break;
            }else{
                $limit_line  = LimitLine::where('city',$city)->where('date_time',date("Y-m-d",time()))->first();
                if(is_null($limit_line)){
                    $host = "https://jisuclwhxx.market.alicloudapi.com";
                    $method = "GET";
                    $appcode = "6966b233733a4e62ae3cd2c182f79cfd";
                    $path = "/vehiclelimit/query";
                    $headers = array();
                    array_push($headers, "Authorization:APPCODE " . $appcode);
                    $querys = "city=".$city."&date=".date("Y-m-d",time());
                    $bodys = "";
                    $url = $host . $path . "?" . $querys;
                    set_time_limit(0);
                    $curl = curl_init();
                    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
                    curl_setopt($curl, CURLOPT_URL, $url);
                    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
                    curl_setopt($curl, CURLOPT_FAILONERROR, false);
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($curl, CURLOPT_HEADER, true);
                    if (1 == strpos("$".$host, "https://"))
                    {
                        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
                    }
                    $city_limit_line = curl_exec($curl);
                    curl_close($curl);
                    if($city_limit_line === FALSE ){
                        $response = Lang::get('error.run_exception');
                        break;
                    }
                    $city_limit_line = json_decode($city_limit_line,true);
                    $result = array();
                    if($city_limit_line['status'] == 0){
                        $result = $city_limit_line['result'];
                    }
                    if(!$result){
                        $response = Lang::get('error.run_exception');
                        break;
                    }
                    $result['date_time'] =  $result['date'];
                    $result['limit_time'] = $result['time'];
                    if(!$result['number']){
                        $result['number'] = '';
                    }
                    unset($result['date']);
                    unset($result['time']);
                    $result['created_at'] = Common::currentTimeString();
                    $limit_line = $result;
                    $result['limit_time'] = json_encode($result['limit_time']);
                    try{
                        LimitLine::insert($result);
                    }catch (Exception $e){
                        Log::error("error", array("system" => "api3.0" ,"event" => "ALYlimitLine", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.city_limit_line_error_12001");
                        //break;
                    }
                }else{
                    $limit_line->limit_time = json_decode($limit_line->limit_time,true);
                }
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'number' => $limit_line,
                )
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "ALYlimitLine", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


   /**
     * @Author:      sqq
     * @DateTime:    2018-11-05 15:29:41
     * @Description: 用户申请语音验证码
     */
    public function voice_check_code()
    {
        $validator = Validator::make(Input::all(),
            array(
                'phone' => 'required|regex:/^1[0123456789][0-9]{9}$/',
                'code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            $messages = $validator->messages();
            if ($validator->fails()) {
                $response = Lang::get("error.user_sms_check_code_args_error_1001");
                break;
            }
            if($messages->has('phone')) {
                $response = Lang::get('error.user_phone_format_error_10007');
                break;
            }

            //todo default area for test
            //获取手机号
            $phone = Input::get('phone');
            $area = '010';
//            $area = Input::get('area');
            $time_out_default = Config::get("user.check_code_time_out");
            $captcha = new Captcha(Input::get('phone'));
//            $check = $captcha->check(Input::get('code'));
//            if(!$check){
//                $response = array("code" => 2,"msg"=>"图片验证码不正确");
//                break;
//            }
            //同一个手机号一天发送登录验证码不能超过3次
            $day_start = date('Y-m-d',time()). ' 00:00:00';
            $day_stop =  date('Y-m-d',time()). ' 23:59:59';
            $day_count = SmsSendRecords::where('phone',$phone)->whereBetween('created_at',array($day_start,$day_stop))->count();
//            if($day_count >3){
//                $response = array("code" => 1,"msg"=>"验证码下发太频繁 "."[".$day_count."]"."[".Request::getClientIp()."]" );
//                break;
//            }
//            //检查手机号是否下发验证码
//            $record = UserCheckCode::getCheckCode($phone,$area);
//            if(!is_null($record)){ //有记录
//                //判断是否超时
//                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
//                    $response = array("code" => 1,"msg"=>"验证码下发太频繁");
//                    break;
//                }else{ //超过限时
//                    UserCheckCode::delCheckCode($phone,$area);
//                }
//            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();

            //调用短信网关发送短信
            try {
                //$sms_send_record_id = Sms::send_message($area,$phone,'您的验证码是'.$check_code.'，有效期6分钟，感谢您选择安惠车服，安惠车服为您提供一站式养车服务。');
                header("Content-type: text/html; charset=utf-8");
                $voice_montnets = Config::get("sms.voice_montnets");
                $VoiceSendConn = new VoiceSendConn($voice_montnets['url']);
                $data = [
                    'userid' => strtoupper($voice_montnets['userid']),
                    'pwd' => $voice_montnets['pwd'],
                    'content' => $check_code,
                    'mobile' => $phone,
                    'msgtype' => 1,
                    'tmplid' => '',
                    'exno' => '',
                    'custid' => '',
                    'url' => $voice_montnets['url'],
                ];

                try {
                    $result = $VoiceSendConn->templateSend($data);
                    if ($result['result'] === 0) {
                        $response = array("code" => 0,"msg"=>"感谢您使用安惠养车，本次登录验证码为：".$check_code);
                    } else {
                        //print_r("模板语音发送失败，错误码：" . $result['result']);
                        $response = Lang::get("error.user_sms_check_code_send_error_10003");
                        break;
                    }
                }catch (Exception $e) {
                    Log::error("error", array("system" => "demo" ,"event" => "voice_check_code", 'input' =>Input::all() ,"exception" => $e));//输出捕获的异常消息，请根据实际情况，添加异常处理代码
                    return false;
                }
                //$status = SmsSendRecords::selectSmsRecord($sms_send_record_id);
                //if(isset($status->status) && $status->status == 1){
                if(1){
//                $status = 1;
//                $sms_send_record_id = 1;
//                if($status  == 1){

                }else{
                    $response = Lang::get("error.user_sms_check_code_send_error_10003");
                    break;
                }

            } catch (Exception $e) {
                Log::error("error", array("system" => "demo" ,"event" => "voice_check_code", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_10003");
                break;
            }

            //记录数据库
//            $data = array(
//                'phone' => $phone,
//                'area' => $area,
//                'check_code' => $check_code,
//                'created_at' => Common::num2DateTime(time()),
//                'out_time_at' => Common::num2DateTime(time() + $time_out_default),
//                'send_id' => $sms_send_record_id,
//            );

//            try {
//                UserCheckCode::insCheckCode($data);
//            } catch (Exception $e) {
//                Log::error("error", array("system" => "wxw" ,"event" => "voice_check_code", 'input' =>Input::all() ,"exception" => $e));
//                $response = Lang::get("error.user_sms_check_code_create_error_1002");
//                break;
//            }

        } while (false);

        Log::info("info", array("system" => "wxw" ,"event" => "voice_check_code", 'input' =>Input::all() ,"output" => $response));
        //return json_encode($response);
        return $response;
    }

}
